package com.duowei.diandan.service;

import android.app.Service;
import android.content.Intent;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.duowei.diandan.activity.WelcomeActivity;
import com.duowei.diandan.app.App;
import com.duowei.diandan.app.OrderList;
import com.duowei.diandan.app.SqlServerDateTime;
import com.duowei.diandan.bean.Ct;
import com.duowei.diandan.bean.DeskStatus;
import com.duowei.diandan.constant.NetConfig;
import com.duowei.diandan.constant.OrderMode;
import com.duowei.diandan.constant.Settings;
import com.duowei.diandan.db.AppDatabase;
import com.duowei.diandan.db.DeskList;
import com.duowei.diandan.db.FoodMenu;
import com.duowei.diandan.db.entry.Auth;
import com.duowei.diandan.db.entry.Cxdmxxx;
import com.duowei.diandan.db.entry.Dccz;
import com.duowei.diandan.db.entry.Dmjyxmsslb;
import com.duowei.diandan.db.entry.Dmkwdydp;
import com.duowei.diandan.db.entry.Dmpzsd;
import com.duowei.diandan.db.entry.Dpzsz;
import com.duowei.diandan.db.entry.Fxhyksz;
import com.duowei.diandan.db.entry.Gklx;
import com.duowei.diandan.db.entry.Jgsz;
import com.duowei.diandan.db.entry.Jycssz;
import com.duowei.diandan.db.entry.Jyxmsz;
import com.duowei.diandan.db.entry.Mzszjbxx;
import com.duowei.diandan.db.entry.Mzszmxxx;
import com.duowei.diandan.db.entry.PaySet;
import com.duowei.diandan.db.entry.RollMessage;
import com.duowei.diandan.db.entry.Tcmc;
import com.duowei.diandan.db.entry.Tcsd;
import com.duowei.diandan.db.entry.Wmlsb;
import com.duowei.diandan.db.entry.Wmlsbjb;
import com.duowei.diandan.db.entry.Wxfwqdz;
import com.duowei.diandan.db.entry.Yhjbqk;
import com.duowei.diandan.event.DownloadStatusEvent;
import com.duowei.diandan.event.ProgressBarEvent;
import com.duowei.diandan.sql.DataSyncSql;
import com.duowei.diandan.util.FileUtils;
import com.duowei.diandan.util.NetUtils;
import com.duowei.diandan.util.Post6Listener;
import com.google.gson.annotations.SerializedName;

import org.greenrobot.eventbus.EventBus;
import org.mozilla.universalchardet.UniversalDetector;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Objects;

import okhttp3.Response;

/**
 * 数据同步
 */
public class DataSyncService extends Service {
    private static final String TAG = "DataSyncService";

    private volatile Looper mLooper;
    private volatile Handler mHandler;
    private Handler mMainHandler;

    private AppDatabase mDb;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate: ");

        HandlerThread thread = new HandlerThread(TAG);
        thread.start();

        mLooper = thread.getLooper();
        mHandler = new Handler(mLooper);
        mMainHandler = new Handler(Looper.getMainLooper());

        mDb = AppDatabase.getDatabase();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand: ");

        mHandler.removeCallbacksAndMessages(null);
        mHandler.post(new DownloadTask());

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: ");
        mLooper.quit();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private class DownloadTask implements Runnable {

        boolean mDbSuccess;

        @Override
        public void run() {
            Log.d(TAG, "DownloadTask: start");

            // 下载前,清空下单数据
            OrderList.getInstance().clearAll();

            String url = NetConfig.getServerUrl();
            if (TextUtils.isEmpty(url)) {
                Log.d(TAG, "没有设置IP");

            } else {
                List<String> imageList = new ArrayList<>();

                mDb.runInTransaction(() -> {
                    try {
                        mDbSuccess = true;

                        // 服务器时间
                        Log.d(TAG, "DownloadTask: 服务器时间更新");
                        sendDownloadMsg(new ProgressBarEvent(5, "下载数据中..."));
                        List<Ct> list = NetUtils.post6(url, SqlServerDateTime.SQL, Ct.class);
                        SqlServerDateTime.getInstance().setServerDateTime(list.get(0).ct);

                        // 用户信息
                        Log.d(TAG, "DownloadTask: 用户信息下载");
                        sendDownloadMsg(new ProgressBarEvent(10, "下载数据中..."));
                        List<Yhjbqk> yhjbqkList = NetUtils.post6(url, Yhjbqk.querySql(), Yhjbqk.class);
                        mDb.yhjbqkDao().deleteAll();
                        mDb.yhjbqkDao().insert(yhjbqkList);

                        // 单品类别
                        Log.d(TAG, "DownloadTask: 单品类别下载");
                        sendDownloadMsg(new ProgressBarEvent(15, "下载数据中..."));
                        List<Dmjyxmsslb> dmjyxmsslbList = NetUtils.post6(url, Dmjyxmsslb.querySql(), Dmjyxmsslb.class);
                        mDb.dmjyxmsslbDao().deleteAll();
                        mDb.dmjyxmsslbDao().insert(dmjyxmsslbList);

                        if (dmjyxmsslbList.size() > 0) {
                            for (Dmjyxmsslb d : dmjyxmsslbList) {
                                if (!TextUtils.isEmpty(d.getLbbm())) {
                                    imageList.add(d.getLbbm());
                                }
                            }
                        }

                        // 单品信息
                        Log.d(TAG, "DownloadTask: 单品信息下载");
                        sendDownloadMsg(new ProgressBarEvent(20, "下载数据中..."));
                        List<Jyxmsz> jyxmszList = NetUtils.post6(url, Jyxmsz.querySql(), Jyxmsz.class);

                        for (Jyxmsz j : jyxmszList) {
                            if (!TextUtils.isEmpty(j.getTm())) {
                                imageList.add(j.getTm());
                            }
                        }

                        mDb.jyxmszDao().deleteAll();
                        mDb.jyxmszDao().insert(jyxmszList);

                        // 套餐Tcmc
                        Log.d(TAG, "DownloadTask: 套餐Tcmc下载");
                        sendDownloadMsg(new ProgressBarEvent(25, "下载数据中..."));
                        List<Tcmc> tcmcList = NetUtils.post6(url, Tcmc.querySql(), Tcmc.class);
                        mDb.tcmcDao().deleteAll();
                        mDb.tcmcDao().insert(tcmcList);

                        // 套餐Tcsd
                        Log.d(TAG, "DownloadTask: 套餐Tcsd下载");
                        sendDownloadMsg(new ProgressBarEvent(30, "下载数据中..."));
                        List<Tcsd> tcsdList = NetUtils.post6(url, Tcsd.querySql(), Tcsd.class);
                        mDb.tcsdDao().deleteAll();
                        mDb.tcsdDao().insert(tcsdList);

                        // 单品组
                        Log.d(TAG, "DownloadTask: 单品组下载");
                        sendDownloadMsg(new ProgressBarEvent(35, "下载数据中..."));
                        List<Dpzsz> dpzszList = NetUtils.post6(url, Dpzsz.querySql(), Dpzsz.class);
                        mDb.dpzszDao().deleteAll();
                        mDb.dpzszDao().insert(dpzszList);

                        if (dpzszList.size() > 0) {
                            for (Dpzsz d : dpzszList) {
                                if (!TextUtils.isEmpty(d.getBm())) {
                                    imageList.add(d.getBm() + "_dpz");
                                }
                            }
                        }

                        // 口味信息
                        Log.d(TAG, "DownloadTask: 口味信息下载");
                        sendDownloadMsg(new ProgressBarEvent(45, "下载数据中..."));
                        List<Dmpzsd> dmpzsds = NetUtils.post6(url, Dmpzsd.querySql(), Dmpzsd.class);
                        mDb.dmpzsdDao().deleteAll();
                        mDb.dmpzsdDao().insert(dmpzsds);

                        // 口味对应单品设置
                        Log.d(TAG, "DownloadTask: 口味对应单品设置下载");
                        sendDownloadMsg(new ProgressBarEvent(50, "下载数据中..."));
                        List<Dmkwdydp> dmkwdydpList = NetUtils.post6(url, Dmkwdydp.querySql(), Dmkwdydp.class);
                        mDb.dmkwdydpDao().deleteAll();
                        mDb.dmkwdydpDao().insert(dmkwdydpList);


                        // 云会员等级-会员价对比
                        Log.d(TAG, "DownloadTask: 云会员等级-会员价对比下载");
                        sendDownloadMsg(new ProgressBarEvent(55, "下载数据中..."));
                        List<Fxhyksz> fxhykszList = NetUtils.post6(url, Fxhyksz.querySql(), Fxhyksz.class);
                        mDb.fxhykszDao().deleteAll();
                        mDb.fxhykszDao().insert(fxhykszList);

                        // 微信服务器地址设置
                        Log.d(TAG, "DownloadTask: 微信服务器地址设置下载");
                        sendDownloadMsg(new ProgressBarEvent(60, "下载数据中..."));
                        List<Wxfwqdz> wxfwqdzList = NetUtils.post6(url, Wxfwqdz.querySql(), Wxfwqdz.class);
                        mDb.wxfwqdzDao().deleteAll();
                        mDb.wxfwqdzDao().insert(wxfwqdzList);

                        // 机构设置
                        Log.d(TAG, "DownloadTask: 机构设置下载");
                        sendDownloadMsg(new ProgressBarEvent(65, "下载数据中..."));
                        List<Jgsz> jgszList = NetUtils.post6(url, Jgsz.querySql(), Jgsz.class);
                        mDb.jgszDao().deleteAll();
                        mDb.jgszDao().insert(jgszList);


                        // 促销单明细信息
                        Log.d(TAG, "DownloadTask: 促销单明细信息下载");
                        sendDownloadMsg(new ProgressBarEvent(70, "下载数据中..."));
                        List<Cxdmxxx> cxdmxxxList = NetUtils.post6(url, Cxdmxxx.querySql(), Cxdmxxx.class);
                        mDb.cxdmxxxDao().deleteAll();
                        mDb.cxdmxxxDao().insert(cxdmxxxList);

                        // 买赠/加价促销设置基本信息
                        Log.d(TAG, "DownloadTask: 买赠/加价促销设置基本信息下载");
                        sendDownloadMsg(new ProgressBarEvent(75, "下载数据中..."));
                        List<Mzszjbxx> mzszjbxxList = NetUtils.post6(url, Mzszjbxx.querySql(), Mzszjbxx.class);
                        mDb.mzszjbxxDao().deleteAll();
                        mDb.mzszjbxxDao().insert(mzszjbxxList);

                        // 买赠/加价促销设置明细信息
                        Log.d(TAG, "DownloadTask: 买赠/加价促销设置明细信息下载");
                        sendDownloadMsg(new ProgressBarEvent(80, "下载数据中..."));
                        List<Mzszmxxx> mzszmxxxList = NetUtils.post6(url, Mzszmxxx.querySql(), Mzszmxxx.class);
                        mDb.mzszmxxxDao().deleteAll();
                        mDb.mzszmxxxDao().insert(mzszmxxxList);

                        // 餐桌
                        Log.d(TAG, "DownloadTask: 餐桌下载");
                        sendDownloadMsg(new ProgressBarEvent(85, "下载数据中..."));
                        List<Jycssz> jycsszList = NetUtils.post6(url, Jycssz.querySql(), Jycssz.class);
                        mDb.jycsszDao().deleteAll();
                        mDb.jycsszDao().insert(jycsszList);

                        // 顾客类型
                        Log.d(TAG, "DownloadTask: 顾客类型下载");
                        sendDownloadMsg(new ProgressBarEvent(90, "下载数据中..."));
                        List<Gklx> gklxList = NetUtils.post6(url, Gklx.querySql(), Gklx.class);
                        mDb.gklxDao().deleteAll();
                        mDb.gklxDao().insert(gklxList);

                        // 支付设置
                        Log.d(TAG, "DownloadTask: 支付设置下载");
                        sendDownloadMsg(new ProgressBarEvent(95, "下载数据中..."));
                        List<PaySet> paySetList = NetUtils.post6(url, PaySet.QUERY_SQL, PaySet.class);
                        mDb.paySetDao().deleteAll();
                        mDb.paySetDao().insert(paySetList);
                        // ----------------
//                        sendDownloadMsg(new ProgressBarEvent(100, "下载数据完成"));

                    } catch (Exception e) {
                        Log.e(TAG, "DownloadTask: 同步数据出错: ", e);
                        sendDownloadMsg(new ProgressBarEvent(-1, "下载数据出错\n" + e.getMessage()));
                        EventBus.getDefault().post(new DownloadStatusEvent(DownloadStatusEvent.Status.ERROR));
                        mDbSuccess = false;

                    }
                });

                // 下载图片
                if (mDbSuccess && Settings.DOWNLOAD_IMAGE) {
                    // 清除图片缓存
                    mMainHandler.post(() -> Glide.get(App.getApp()).clearMemory());
                    Glide.get(App.getApp()).clearDiskCache();

                    // foodImages
                    File foodImagesFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Dw/food_images");
                    if (foodImagesFile.exists()) {
                        FileUtils.deleteFolder(foodImagesFile);
                    }
                    //noinspection ResultOfMethodCallIgnored
                    foodImagesFile.mkdirs();
                    try {
                        FileUtils.createNoMediaFile(foodImagesFile);
                    } catch (IOException e) {
                        Log.e(TAG, e.getMessage());
                    }

                    int size = imageList.size() + 10;
                    for (int i = 0; i < imageList.size(); i++) {
                        String fileName = imageList.get(i) + ".png";
                        try {
                            sendDownloadMsg(new ProgressBarEvent(100 * i / size, "下载图片中..."));
                            File savedFile = new File(foodImagesFile, fileName);
                            NetUtils.downloadImage(NetConfig.getServerFoodImagesUrl() + fileName, savedFile);
                        } catch (IOException e) {
                            Log.e(TAG, "下载图片出错", e);
                        }
                    }

                    // welcome_images
                    File welcomeImagesFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Dw/welcome_images");
                    if (welcomeImagesFile.exists()) {
                        FileUtils.deleteFolder(welcomeImagesFile);
                    }
                    //noinspection ResultOfMethodCallIgnored
                    welcomeImagesFile.mkdirs();
                    try {
                        FileUtils.createNoMediaFile(welcomeImagesFile);
                    } catch (IOException e) {
                        Log.e(TAG, e.getMessage());
                    }
                    for (int i = 1; i <= 10; i++) {
                        String fileName = String.format(Locale.CHINA, "%02d.png", i);
                        try {
                            sendDownloadMsg(new ProgressBarEvent(100 * (imageList.size() + i) / size, "下载图片中..."));
                            File savedFile = new File(welcomeImagesFile, fileName);
                            NetUtils.downloadImage(NetConfig.getServerWelcomeImagesUrl() + fileName, savedFile);
                        } catch (IOException e) {
                            Log.e(TAG, "下载图片出错", e);
                        }
                    }
                }

                // 下载完成
                if (mDbSuccess) {
                    sendDownloadMsg(new ProgressBarEvent(100, "数据处理中,请等待..."));

                    // 处理餐桌列表
                    if (OrderMode.COMMIT == Settings.ORDER_MODE) {
                        DeskList.getInstance().createGroupList();
                    }

                    mHandler.postDelayed(new SyncTask(url), 1000);
                }
            }

            Log.d(TAG, "DownloadTask: end");
        }

        void sendDownloadMsg(ProgressBarEvent event) {
            EventBus.getDefault().post(event);
        }
    }

    private class SyncTask implements Runnable {

        private String mUrl;
        private boolean mIsFirst;
        private List<String> mSyncTableList = new ArrayList<>();

        public SyncTask(String url) {
            mUrl = url;
            mIsFirst = true;

            mSyncTableList.add(Dmjyxmsslb.class.getSimpleName());
            mSyncTableList.add(Jyxmsz.class.getSimpleName());
            mSyncTableList.add(Tcmc.class.getSimpleName());
            mSyncTableList.add(Tcsd.class.getSimpleName());
            mSyncTableList.add(Dpzsz.class.getSimpleName());
            mSyncTableList.add(Dmpzsd.class.getSimpleName());
            mSyncTableList.add(Dmkwdydp.class.getSimpleName());
            mSyncTableList.add(Fxhyksz.class.getSimpleName());
            mSyncTableList.add(Wxfwqdz.class.getSimpleName());
            mSyncTableList.add(Jgsz.class.getSimpleName());
            mSyncTableList.add(Cxdmxxx.class.getSimpleName());
            mSyncTableList.add(Mzszjbxx.class.getSimpleName());
            mSyncTableList.add(Mzszmxxx.class.getSimpleName());
        }

        @Override
        public void run() {
            Log.d(TAG, "SyncTask: start");

            try {
                // --
                if (mIsFirst) {
                    NetUtils.post7(mUrl, DataSyncSql.createTableSql() + DataSyncSql.deleteTableSql());
                }

                // --
                StringBuilder sql = new StringBuilder();
                for (String tableName : mSyncTableList) {
                    sql.append(DataSyncSql.checkSyncSql(tableName));
                }
                NetUtils.post7(mUrl, sql.toString());

                // 表同步
                List<Table> tableList = NetUtils.post6(mUrl, DataSyncSql.querySql(), Table.class);

                // 判断jyxmsz是否变化,有变化时,同时更新tcmc、tcsd
                boolean findJyxmszUpdated = false;
                for (Table t : tableList) {
                    if (t.name.equals(Jyxmsz.class.getSimpleName())) {
                        findJyxmszUpdated = true;
                        break;
                    }
                }
                if (findJyxmszUpdated) {
                    tableList.add(new Table(Tcmc.class.getSimpleName()));
                    tableList.add(new Table(Tcsd.class.getSimpleName()));
                }

                //
                boolean foodDataUpdate; // 和食物相关的表数据是否变化
                //noinspection RedundantIfStatement
                if (mIsFirst) {
                    // 第一次需要更新
                    foodDataUpdate = true;
                } else {
                    foodDataUpdate = false;
                }

                for (Table t : tableList) {
                    String tableName = t.name;
                    if (!TextUtils.isEmpty(tableName)) {

                        if (tableName.equals(Dmjyxmsslb.class.getSimpleName())) {
                            foodDataUpdate = true;

                            List<Dmjyxmsslb> dmjyxmsslbList = NetUtils.post6(mUrl, Dmjyxmsslb.querySql(), Dmjyxmsslb.class);
                            mDb.dmjyxmsslbDao().deleteAll();
                            mDb.dmjyxmsslbDao().insert(dmjyxmsslbList);

                            NetUtils.post7(mUrl, DataSyncSql.setSyncedSql(tableName));
                        }

                        if (tableName.equals(Jyxmsz.class.getSimpleName())) {
                            foodDataUpdate = true;

                            List<Jyxmsz> jyxmszList = NetUtils.post6(mUrl, Jyxmsz.querySql(), Jyxmsz.class);
                            mDb.jyxmszDao().deleteAll();
                            mDb.jyxmszDao().insert(jyxmszList);

                            NetUtils.post7(mUrl, DataSyncSql.setSyncedSql(tableName));
                        }

                        if (tableName.equals(Tcmc.class.getSimpleName())) {
                            foodDataUpdate = true;

                            List<Tcmc> tcmcList = NetUtils.post6(mUrl, Tcmc.querySql(), Tcmc.class);
                            mDb.tcmcDao().deleteAll();
                            mDb.tcmcDao().insert(tcmcList);

                            NetUtils.post7(mUrl, DataSyncSql.setSyncedSql(tableName));
                        }

                        if (tableName.equals(Tcsd.class.getSimpleName())) {
                            foodDataUpdate = true;

                            List<Tcsd> tcsdList = NetUtils.post6(mUrl, Tcsd.querySql(), Tcsd.class);
                            mDb.tcsdDao().deleteAll();
                            mDb.tcsdDao().insert(tcsdList);

                            NetUtils.post7(mUrl, DataSyncSql.setSyncedSql(tableName));
                        }

                        if (tableName.equals(Dpzsz.class.getSimpleName())) {
                            foodDataUpdate = true;

                            List<Dpzsz> dpzszList = NetUtils.post6(mUrl, Dpzsz.querySql(), Dpzsz.class);
                            mDb.dpzszDao().deleteAll();
                            mDb.dpzszDao().insert(dpzszList);

                            NetUtils.post7(mUrl, DataSyncSql.setSyncedSql(tableName));
                        }

                        if (tableName.equals(Dmpzsd.class.getSimpleName())) {
                            foodDataUpdate = true;

                            List<Dmpzsd> dmpzsds = NetUtils.post6(mUrl, Dmpzsd.querySql(), Dmpzsd.class);
                            mDb.dmpzsdDao().deleteAll();
                            mDb.dmpzsdDao().insert(dmpzsds);

                            NetUtils.post7(mUrl, DataSyncSql.setSyncedSql(tableName));
                        }

                        if (tableName.equals(Dmkwdydp.class.getSimpleName())) {
                            foodDataUpdate = true;

                            List<Dmkwdydp> dmkwdydpList = NetUtils.post6(mUrl, Dmkwdydp.querySql(), Dmkwdydp.class);
                            mDb.dmkwdydpDao().deleteAll();
                            mDb.dmkwdydpDao().insert(dmkwdydpList);

                            NetUtils.post7(mUrl, DataSyncSql.setSyncedSql(tableName));
                        }

                        if (tableName.equals(Fxhyksz.class.getSimpleName())) {
                            foodDataUpdate = true;

                            List<Fxhyksz> fxhykszList = NetUtils.post6(mUrl, Fxhyksz.querySql(), Fxhyksz.class);
                            mDb.fxhykszDao().deleteAll();
                            mDb.fxhykszDao().insert(fxhykszList);

                            NetUtils.post7(mUrl, DataSyncSql.setSyncedSql(tableName));
                        }

                        if (tableName.equals(Wxfwqdz.class.getSimpleName())) {
                            foodDataUpdate = true;

                            List<Wxfwqdz> wxfwqdzList = NetUtils.post6(mUrl, Wxfwqdz.querySql(), Wxfwqdz.class);
                            mDb.wxfwqdzDao().deleteAll();
                            mDb.wxfwqdzDao().insert(wxfwqdzList);

                            NetUtils.post7(mUrl, DataSyncSql.setSyncedSql(tableName));
                        }

                        if (tableName.equals(Jgsz.class.getSimpleName())) {
                            foodDataUpdate = true;

                            List<Jgsz> jgszList = NetUtils.post6(mUrl, Jgsz.querySql(), Jgsz.class);
                            mDb.jgszDao().deleteAll();
                            mDb.jgszDao().insert(jgszList);

                            NetUtils.post7(mUrl, DataSyncSql.setSyncedSql(tableName));
                        }

                        if (tableName.equals(Cxdmxxx.class.getSimpleName())) {
                            foodDataUpdate = true;

                            List<Cxdmxxx> cxdmxxxList = NetUtils.post6(mUrl, Cxdmxxx.querySql(), Cxdmxxx.class);
                            mDb.cxdmxxxDao().deleteAll();
                            mDb.cxdmxxxDao().insert(cxdmxxxList);

                            NetUtils.post7(mUrl, DataSyncSql.setSyncedSql(tableName));
                        }

                        if (tableName.equals(Mzszjbxx.class.getSimpleName())) {
                            foodDataUpdate = true;

                            List<Mzszjbxx> mzszjbxxList = NetUtils.post6(mUrl, Mzszjbxx.querySql(), Mzszjbxx.class);
                            mDb.mzszjbxxDao().deleteAll();
                            mDb.mzszjbxxDao().insert(mzszjbxxList);

                            NetUtils.post7(mUrl, DataSyncSql.setSyncedSql(tableName));
                        }

                        if (tableName.equals(Mzszmxxx.class.getSimpleName())) {
                            foodDataUpdate = true;

                            List<Mzszmxxx> mzszmxxxList = NetUtils.post6(mUrl, Mzszmxxx.querySql(), Mzszmxxx.class);
                            mDb.mzszmxxxDao().deleteAll();
                            mDb.mzszmxxxDao().insert(mzszmxxxList);

                            NetUtils.post7(mUrl, DataSyncSql.setSyncedSql(tableName));
                        }
                    }
                }
                // FoodMenu刷新数据
                if (foodDataUpdate) {
                    Log.d(TAG, "SyncTask: 更新表数据-" + tableList.toString());

                } else {
                    Log.d(TAG, "SyncTask: 未发现表需要更新");
                }

                if (foodDataUpdate) {
                    Log.d(TAG, "SyncTask: FoodMenu刷新");

                    FoodMenu.getInstance().updateData();
                    FoodMenu.getInstance().setRefreshData();
                }

                // -----------
                FoodMenu.getInstance().computeMzszjbxxAndMzszmxxx();
                FoodMenu.getInstance().computeCxdmxxx();

                // -----------------------------------------------

                // 下单模式处理
                if (OrderMode.COMMIT == Settings.ORDER_MODE) {
                    // dccz表处理
                    Dccz dccz = mDb.dcczDao().findOne();
                    String dcczSql;
                    if (dccz == null) {
                        dcczSql = Dccz.deleteByBy1Sql(Settings.DEFAULT_YHJBQK.getYhbh());
                    } else {
                        dcczSql = Dccz.insertSql(dccz);
                    }
                    NetUtils.post7(mUrl, dcczSql);

                    // 餐桌占用同步
                    List<DeskStatus> deskStatusList = NetUtils.post6(mUrl, DeskStatus.querySql(), DeskStatus.class);
                    DeskList.getInstance().handleDeskStatus(deskStatusList);

                    // WMLSBJB WMLSB 数据同步(下单模式)
                    Wmlsbjb wmlsbjb = mDb.wmlsbjbDao().findOne();
                    if (wmlsbjb != null && !TextUtils.isEmpty(wmlsbjb.getWmdbh())) {
                        String wmdbh = wmlsbjb.getWmdbh();

                        List<Wmlsbjb> remoteWmlsbjbList = NetUtils.post6(mUrl, Wmlsbjb.toQuerySql(wmdbh), Wmlsbjb.class);
                        if (remoteWmlsbjbList.size() == 0) {
                            // 删除本地订单数据
                            OrderList.getInstance().clearAll();

                            mHandler.post(() -> {
                                Toast.makeText(DataSyncService.this, "未发现当前单号,返回开始界面", Toast.LENGTH_SHORT).show();

                                Intent intent = new Intent(DataSyncService.this, WelcomeActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(intent);
                            });

                        } else if (remoteWmlsbjbList.size() == 1) {
                            Wmlsbjb remoteWmlsbjb = remoteWmlsbjbList.get(0);

                            if ("1".equals(remoteWmlsbjb.getSfyjz())) {
                                // 已结账处理
                                OrderList.getInstance().clearAll();

                                mHandler.post(() -> {
                                    Toast.makeText(DataSyncService.this, "已结账,返回开始界面", Toast.LENGTH_SHORT).show();

                                    Intent intent = new Intent(DataSyncService.this, WelcomeActivity.class);
                                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                    startActivity(intent);
                                });
                            } else {
                                //
                                if (!wmlsbjb.equals(remoteWmlsbjb)) {
                                    mDb.wmlsbjbDao().update(remoteWmlsbjb);

                                    Log.d(TAG, "SyncTask: 更新wmlsbjb");
                                }

                                //
                                List<Wmlsb> wmlsbList = mDb.wmlsbDao().findAllRemote();
                                List<Wmlsb> remoteWmlsbList = NetUtils.post6(mUrl, Wmlsb.toQuerySql(wmdbh), Wmlsb.class);

                                if (!wmlsbList.containsAll(remoteWmlsbList)
                                        || !remoteWmlsbList.containsAll(wmlsbList)) {

                                    mDb.getOpenHelper().getWritableDatabase().execSQL("DELETE FROM wmlsb WHERE xh IS NOT NULL");
                                    mDb.wmlsbDao().insert(remoteWmlsbList);

                                    OrderList.getInstance().handleWmlsb();
                                    OrderList.getInstance().performRefresh();

                                    Log.d(TAG, "SyncTask: 更新wmlsb");
                                }
                            }
                        }
                    }
                }

                // -----------------------
                // 滚动信息更新
                if (Settings.ROLL_MESSAGE_ENABLED) {
                    Response response = NetUtils.get(NetConfig.getRollMessageUrl());
                    if (response.code() == 200) {
                        byte[] bytes = response.body().bytes();

                        UniversalDetector detector = new UniversalDetector(null);
                        detector.handleData(bytes, 0, bytes.length);
                        detector.dataEnd();

                        String text = new String(bytes,detector.getDetectedCharset());

                        RollMessage rollMessage = mDb.rollMessageDao().findOne();

                        if (rollMessage == null) {
                            RollMessage rollMessage2 = new RollMessage();
                            rollMessage2.setText(text);
                            mDb.rollMessageDao().insert(rollMessage2);
                        } else {
                            if (!Objects.equals(text, rollMessage.getText())) {
                                rollMessage.setText(text);
                                mDb.rollMessageDao().update(rollMessage);
                            }
                        }
                    } else {
                        mDb.rollMessageDao().deleteAll();
                    }
                }

                // ------------------------
                if (mIsFirst) {
                    mIsFirst = false;
                    // 第一次下载,处理数据完成,进入开始点餐界面
                    EventBus.getDefault().post(new DownloadStatusEvent(DownloadStatusEvent.Status.SUCCESS));
                }

            } catch (IOException e) {
                Log.e(TAG, "SyncTask: ", e);
            }

            Log.d(TAG, "SyncTask: end");

            //
            if (OrderMode.COMMIT == Settings.ORDER_MODE) {
                mHandler.postDelayed(this, 2 * 1000);

            } else {
                mHandler.postDelayed(this, 3 * 1000);
            }
        }
    }

    private class Table {
        @SerializedName("table_name")
        String name;

        public Table() {
        }

        public Table(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return name;
        }
    }
}
